<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of User
 *
 * @author Kam
 */
class Application_Model_DAO_User extends My_DAO_Abstract {

    const DB_USER = 'User';

    public function isUserInRole($role, $user = null) {
        
    }

    public function get($userId) {
        if ($userId && !empty($userId) && $userId > 0) {
            return $this->getDbTable()->get($userId);
        }
        return null;
    }

    public function update($userId, $data) {
        $this->getDbTable()->update($data, $userId);
    }

    public function login($email, $pass) {
        $user = $this->getDbTable()->select()
                        ->where('email = ?', $email)
                        ->where('pass = SHA1(CONCAT(pass_salt, "#", ?))', $pass)
                        ->query()->fetch();
        if (!$user || empty($user)) {
            return null;
        }
        $this->getDbTable()->update(array('last_login_date' => date(My_Db_Table::DATE_TIME_PATTERN)), 'user_id = ' . $user['user_id']);

        $userObj = new Application_Model_UserBean();
        $userObj->user_id = $user['user_id'];
        $userObj->email = $user['email'];
        Zend_Auth::getInstance()->getStorage()->write($userObj);

        unset($user['pass']);
        unset($user['pass_salt']);
        return $user;
    }

    public function register($data) {
        $passSalt = $this->getDbTable()->createNewCode();
        $user = array(
            'email' => $data['email'],
            'pass_salt' => $passSalt,
            'pass' => sha1($passSalt . '#' . $data['pass']),
            'contact_email' => $data['email'],
        );

        $userId = $this->getDbTable()->insert($user);
        $user = $this->getDbTable()->get($userId);
        return $user;
    }

    public function isPasswordValid($pass, $userId) {
        $user = $this->getDbTable()->select()
                        ->where('user_id = ?', $userId)
                        ->where('pass = SHA1(CONCAT(pass_salt, "#", ?))', $pass)
                        ->query()->fetch();
        return !empty($user);
    }

    public function changePassword($userId, $data) {
        $passSalt = $this->getDbTable()->createNewCode();
        $user = array(
            'pass_salt' => $passSalt,
            'pass' => sha1($passSalt . '#' . $data['newPassword'])
        );

        $userId = $this->getDbTable()->update($user, $userId);
    }

    protected function getDbTableNameMap() {
        return array(
            self::DB_USER => 'Application_Model_DbTable_User',
        );
    }

    protected function getDefaultDbTableName() {
        return self::DB_USER;
    }

}
